package com.denlaku.longan.filter;

import com.denlaku.longan.Const;
import com.denlaku.longan.core.RequestContext;
import com.denlaku.longan.core.RequestContextManager;
import com.denlaku.longan.vo.User;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @author tianx
 */
public class RequestContextFilter extends HttpFilter {
    private static final String HEADER_X_PREFIX = "x-";

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            HttpSession session = request.getSession(false);
            Object userInfo = session.getAttribute(Const.KEY_USER_INFO);
            if (userInfo instanceof User) {
                RequestContext requestContext = new RequestContext();
                requestContext.setUser((User) userInfo);
                requestContext.setHeaderMap(initHeaderMap(request));
                RequestContextManager.setCurrent(requestContext);
            }
            super.doFilter(request, response, chain);
        } finally {
            RequestContextManager.remove();
        }
    }

    private Map<String, Object> initHeaderMap(HttpServletRequest request) {
        Map<String, Object> headerMap = new HashMap<>(16);
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement().toLowerCase(Locale.ROOT);
            if (headerName.startsWith(HEADER_X_PREFIX)) {
                headerMap.put(headerName, request.getHeader(headerName));
            }
        }
        return headerMap;
    }

}
